package com.system.borrow.fragment;

import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.system.borrow.Constant.URLDefind;
import com.system.borrow.MyApplication;
import com.system.borrow.R;
import com.system.borrow.activity.LookActivity;
import com.system.borrow.activity.MyMsgActivity;
import com.system.borrow.activity.SettingActivity;
import com.system.borrow.activity.UserInfoNewActivity;
import com.system.borrow.bean.CustomerDTO;
import com.system.borrow.bean.GloData;
import com.system.borrow.callback.DialogCallback;
import com.system.borrow.http.utils.OkHttpUtils;
import com.system.borrow.utils.SharedPreferencesUtil;
import com.system.borrow.widget.CircleImageView;
import com.zzti.fengyongge.imagepicker.PhotoSelectorActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.List;

import okhttp3.Request;
import okhttp3.Response;

/**
 * ================================================
 * 作    者：LuCenly(落尘)
 * 版    本：1.0
 * 创建日期：2016/11/17 23:34
 * 描    述：TODO
 * ================================================
 */
public class MyFragment extends Fragment implements View.OnClickListener{
    View myView;
    LinearLayout ll_msg,ll_look,ll_set,ll_my_login;
    FrameLayout fl_my;
    TextView tv_name,tv_tel;
    public static MyFragment myFragment;
    CircleImageView iv_head;
    ImageView iv_unread;
    DisplayImageOptions options = new DisplayImageOptions.Builder().showImageForEmptyUri(R.drawable.head1)// 设置图片Uri为空或是错误的时候显示的图片
            .showImageOnFail(R.drawable.head1) // 设置图片加载/解码过程中错误时候显示的图片
            .cacheInMemory(true)// 设置下载的图片是否缓存在内存中
            .cacheOnDisk(true)// 设置下载的图片是否缓存在SD卡中
            .considerExifParams(true) // 是否考虑JPEG图像EXIF参数（旋转，翻转）
            .imageScaleType(ImageScaleType.IN_SAMPLE_INT)// 设置图片以如何的编码方式显示
            // .decodingOptions(BitmapFactory.Options
            // decodingOptions)//设置图片的解码配置
            .delayBeforeLoading(0)// int delayInMillis为你设置的下载前的延迟时间
            // 设置图片加入缓存前，对bitmap进行设置
            // .preProcessor(BitmapProcessor preProcessor)
            .resetViewBeforeLoading(true)// 设置图片在下载前是否重置，复位
//				.displayer(new SimpleBitmapDisplayer())// 是否图片加载好后渐入的动画时间，可能会出现闪动
            .displayer(new FadeInBitmapDisplayer(1000))
            .build();
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (myView == null) {
            myView = inflater.inflate(R.layout.fragment_my, container, false);
        } else {
            ViewParent parent = myView.getParent();
            if (parent instanceof ViewGroup) {
                ((ViewGroup) parent).removeView(myView);
            }
        }
        myFragment = this;
        initView(myView);
        initListener();
        loadData();
        return myView;
    }


    public void loadData() {
        if(GloData.getCustomerDTO()!=null){
            tv_name.setText(GloData.getCustomerDTO().getName());
            tv_tel.setText(GloData.getCustomerDTO().getMobile());
            if(GloData.getCustomerDTO().getHeadImg()!=null){
                MyApplication.imageLoader.displayImage(GloData.getCustomerDTO().getHeadImg(),iv_head,options);
            }
        }
    }

    private void initListener() {
        ll_msg.setOnClickListener(this);
        ll_look.setOnClickListener(this);
        ll_set.setOnClickListener(this);
        fl_my.setOnClickListener(this);
        ll_my_login.setOnClickListener(this);
        iv_head.setOnClickListener(this);
    }

    private void initView(View myView) {
        ll_msg = (LinearLayout) myView.findViewById(R.id.ll_msg);
        ll_look = (LinearLayout) myView.findViewById(R.id.ll_look);
        ll_set = (LinearLayout) myView.findViewById(R.id.ll_set);
        fl_my = (FrameLayout) myView.findViewById(R.id.fl_my);
        ll_my_login = (LinearLayout)myView.findViewById(R.id.ll_my_login);
        tv_name = (TextView) myView.findViewById(R.id.tv_name);
        tv_tel = (TextView) myView.findViewById(R.id.tv_tel);
        iv_head = (CircleImageView) myView.findViewById(R.id.iv_head);
        iv_unread = (ImageView) myView.findViewById(R.id.iv_unread);
    }
    public void setUnRead(boolean isLook){
        if(isLook){
            iv_unread.setVisibility(View.VISIBLE);
        }else{
            iv_unread.setVisibility(View.GONE);
        }
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.ll_msg:
                Intent msg_intent = new Intent(getActivity(), MyMsgActivity.class);
                startActivity(msg_intent);
                break;
            case R.id.ll_look:
                Intent look_intent = new Intent(getActivity(), LookActivity.class);
                startActivity(look_intent);
                break;
            case R.id.ll_set:
                Intent set_intent = new Intent(getActivity(), SettingActivity.class);
                startActivity(set_intent);
                break;
            case R.id.fl_my:
                Intent user_intent = new Intent(getActivity(), UserInfoNewActivity.class);
                startActivity(user_intent);
                break;
            case R.id.ll_my_login:
                Intent login_intent = new Intent(getActivity(), UserInfoNewActivity.class);
                startActivity(login_intent);
                break ;
            case R.id.iv_head:
                Intent intent = new Intent(getActivity(), PhotoSelectorActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                intent.putExtra("limit", 1 );//number是选择图片的数量
                startActivityForResult(intent, 0);
                break;
        }
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 0:
                if (data != null) {
                    List<String> paths = (List<String>) data.getExtras().getSerializable("photos");//path是选择拍照或者图片的地址数组
                    //处理代码
                    String path = paths.get(0);
//                    MyApplication.imageLoader.displayImage(path,iv_head);
                    upLoadHead(path);
                }
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void upLoadHead(String path) {
        File file = new File(path);
        OkHttpUtils.post(URLDefind.UPLOAD)
                .tag(this)
                .params("headImg",file)
                .execute(new DialogCallback<String>(getActivity(),String.class,"上传中...") {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            int statusCode = jsonObject.getInt("statusCode");
                            Gson gson = new Gson();
                            if(statusCode ==200){
                                Toast.makeText(getActivity(),"上传成功!",Toast.LENGTH_SHORT).show();
                                String data = jsonObject.getString("data");
                                TypeToken<CustomerDTO> token = new TypeToken<CustomerDTO>(){};
                                final CustomerDTO customer = gson.fromJson(data,token.getType());
                                GloData.setCustomerDTO(customer);
                                MyApplication.imageLoader.displayImage(customer.getHeadImg(),iv_head);
                                SharedPreferencesUtil.putString(getActivity(),"custormer","custormer",gson.toJson(customer));
                            }else{
//                                ToastShow(jsonObject.getString("message"));
                                Toast.makeText(getActivity(),jsonObject.getString("message"),Toast.LENGTH_SHORT).show();
                            }

                        }catch (JSONException e){
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onCacheResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {

                    }
                });
    }
}
